package twoD.IsoPfem;

import java.util.ArrayList;

public class Triangle extends Geometry {

	public Triangle(Node... nodes) {
		super(nodes);
	}

	public Triangle(ArrayList<Node> nodes) {
		super(nodes.get(0), nodes.get(1), nodes.get(2));
	}

	public Triangle(IFace p) {
		super(p.getNodes(0), p.getNodes(1), p.getNodes(2));
		int[] seq = checkEdge(p.getNodes(0), p.getNodes(1), p.getNodes(2),
				p.getEdges(0), p.getEdges(1), p.getEdges(2));
		if (seq == null)
			throw new IllegalArgumentException(
					"The provided edges are not compatible with nodes");
		addEdge(p.getEdges(seq[0]));
		addEdge(p.getEdges(seq[1]));
		addEdge(p.getEdges(seq[2]));
	}

	/**
	 * check the compatibility of the edge provided to find the correct sequende
	 * of edges feed into the geometry. In order for the enumeration to run
	 * correctly, the edge need to be in the sequence of: edge 0 contains n0, n1
	 * edge 1 contains n1, n2 edge 2 contains n2, n0
	 * 
	 * @param e1
	 * @param e2
	 * @param e3
	 * @return the sequence of edge following above convention
	 */
	private int[] checkEdge(Node n0, Node n1, Node n2, IEdge e0, IEdge e1,
			IEdge e2) {
		int[] tmp = new int[3];
		if (e0.contain(n0, n1)) {
			tmp[0] = 0;
			if (e1.contain(n1, n2)) {
				tmp[1] = 1;
				if (e2.contain(n0, n2))
					tmp[2] = 2;
				else
					return null;
			} else if (e1.contain(n0, n2)) {
				tmp[1] = 2;
				if (e2.contain(n1, n2))
					tmp[2] = 1;
				else
					return null;
			} else
				return null;// invalid case
		} else if (e0.contain(n1, n2)) {
			tmp[0] = 1;
			if (e1.contain(n0, n2)) {
				tmp[1] = 2;
				if (e2.contain(n0, n1))
					tmp[2] = 0;
				else
					return null;
			} else if (e1.contain(n0, n1)) {
				tmp[1] = 0;
				if (e2.contain(n0, n2))
					tmp[2] = 2;
				else
					return null;
			} else
				return null;// invalid case
		} else if (e0.contain(n0, n2)) {
			tmp[0] = 2;
			if (e1.contain(n1, n2)) {
				tmp[1] = 1;
				if (e2.contain(n0, n1))
					tmp[2] = 0;
				else
					return null;
			} else if (e1.contain(n0, n1)) {
				tmp[1] = 0;
				if (e2.contain(n1, n2))
					tmp[2] = 1;
				else
					return null;
			} else
				return null;// invalid case
		} else
			return null;// invalid case

		int[] seq = new int[3];
		for (int i = 0; i < 3; i++)
			seq[tmp[i]] = i;

		return seq;
	}
}
